package com.lei.tong.db;

import android.content.Context;

import com.lei.tong.log_utlis.LogUtils;

public class DbManger {
    private static final String DATABASE_NAME = "student_data";
    private static DbManger instance;

    private DaoSession daoSession;
    private DaoMaster.DevOpenHelper devOpenHelper;
    private DaoMaster daoMaster;

    public static  DbManger getInstance(){
        if (instance == null){
            //同步锁
            synchronized (DbManger.class){
                if (instance == null){
                    instance = new DbManger();
                }
            }
        }
        return instance;
    }

    public DaoSession getDaoSession(){
        return daoSession;
    }

    //数据库初始化
    public void initDb(Context context){
        devOpenHelper = new MySQLiteOpenHelper(context,DATABASE_NAME,null);
        daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        daoSession = daoMaster.newSession();
        LogUtils.e("打开了数据库"+devOpenHelper.getDatabaseName());
    }
    /**
     * 关闭数据库
     */
    public void closedb(){
        if (devOpenHelper!=null){
            LogUtils.e("关闭了数据库"+devOpenHelper.getDatabaseName());
        }
        //关闭session
        closeSession();
        //关闭helper
        closeHelper();
    }

    private void closeSession() {
        if (daoSession!=null){
            daoSession.clear();
            daoSession=null;
        }
    }
    private void closeHelper(){
        if (devOpenHelper!=null){
            devOpenHelper.close();
            devOpenHelper=null;
        }
    }
}
